import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from datetime import datetime, timedelta
import ccxt
import pandas as pd
from decimal import Decimal

from config.settings import EXCHANGES, RiskConfig, AnalysisConfig
from backtest.engine import BacktestEngine
from backtest.data_handler import HistoricalDataHandler
from strategies.moving_average_strategy import MovingAverageStrategy
from analysis.market_analyzer import MarketAnalyzer
from risk.risk_manager import RiskManager

def main():
    # 设置回测参数
    start_date = datetime(2023, 1, 1)
    end_date = datetime(2023, 12, 31)
    symbols = ['BTC/USDT', 'ETH/USDT']
    timeframe = '1h'
    initial_capital = 100000.0
    
    # 初始化交易所
    exchanges = {}
    for name, config in EXCHANGES.items():
        exchange = getattr(ccxt, name)({
            'apiKey': config.api_key,
            'secret': config.api_secret
        })
        exchanges[name] = exchange
        
    try:
        # 初始化组件
        data_handler = HistoricalDataHandler(
            exchanges=exchanges,
            symbols=symbols,
            start_date=start_date,
            end_date=end_date,
            timeframe=timeframe
        )
        
        market_analyzer = MarketAnalyzer(config=AnalysisConfig())
        risk_manager = RiskManager(config=RiskConfig())
        
        # 创建策略
        strategy = MovingAverageStrategy(
            market_analyzer=market_analyzer,
            risk_manager=risk_manager,
            short_window=5,
            long_window=20
        )
        
        # 创建回测引擎
        engine = BacktestEngine(
            data_handler=data_handler,
            strategy=strategy,
            risk_manager=risk_manager,
            initial_capital=initial_capital
        )
        
        # 运行回测
        print("开始回测...")
        engine.run_backtest()
        
        # 获取回测结果
        results = engine.get_backtest_results()
        
        # 打印回测结果
        print("\n=== 回测结果 ===")
        print(f"初始资金: ${results['Initial Capital']:,.2f}")
        print(f"最终资金: ${results['Final Capital']:,.2f}")
        print(f"总收益率: {results['Total Return']*100:.2f}%")
        print(f"夏普比率: {results['Sharpe Ratio']:.2f}")
        print(f"最大回撤: {results['Max Drawdown']*100:.2f}%")
        print(f"总手续费: ${results['Total Commission']:,.2f}")
        
        # 保存详细结果到CSV
        results['Positions History'].to_csv('backtest_positions.csv')
        results['Holdings History'].to_csv('backtest_holdings.csv')
        print("\n详细结果已保存到 backtest_positions.csv 和 backtest_holdings.csv")
        
    except Exception as e:
        print(f"回测过程中出错: {str(e)}")
        raise
        
if __name__ == "__main__":
    main()
